<template>
	<view>
		<canvas :id="canvasId" :canvas-id="canvasId" :style="{width:labelWidth+'px',height:labelHeight+'px'}"
			style="position: fixed;left: -9999px;top: -9999px;"></canvas>
		<view style="padding: 10rpx 0;">
			<view class="" v-for="(item,index) in deviceList" class="item">
				<view class="name">
					名称:{{item.name}}
					<view>
						设备ID:{{item.deviceId}}
					</view>
				</view>
				<view class="btn" :class="item.deviceId===activeDeviceId?'active-btn':''" @click="printConnect(index,item)">{{item.deviceId===activeDeviceId?'已连接':'断开连接'}}</view>
			</view>
			<view v-if="deviceList.length==0 && !loading">
				<u-empty mode="data" text="暂无打印机设备"></u-empty>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		LPAPIFactory,
		LPAUtils
	} from 'lpapi-ble-uni'
	var lpapi
	export default {
		data() {
			return {
				canvasId: "lpapi-ble-uni1",
				labelWidth: 960,
				labelHeight: 960,
				deviceList: [],
				activeDeviceId:"548784654516",
				deviceIndex: 99999,
				isLark: false,
				printCanvas: false,
				printMode: 0
			}
		},
		onLoad() {

		},
		onShow() {
			// 跳转到其他页面，然后返回当前页面后，必须更新 lpapi示例中的 绘制上下文，否则绘制上下文错误的话就无法正常绘制了。
			if (this.context) {
				this.lpapi.setDrawContext(this.context);
			}
		},
		mounted() {
			this.lpapi = LPAPIFactory.getInstance({
				// 日志信息显示级别，值为 0 - 4，0表示不显示调试信息，4表示显示所有调试信息
				showLog: 4,
			});
			// 搜索蓝牙设备
			this.lpapi.startBleDiscovery({
				timeout: 0,
				deviceFound: (devices) => {
					this.onDeviceFound(devices);
				},
			});
			uni.getSystemInfo({
				complete: (res) => {
					this.mSystemInfo = res;
				},
			});
			// 微信小程序、支付宝小程序可以通过 createSelectorQuery 来获取Canvas实例。
			if (this.isWeiXin || this.isAlipay) {
				setTimeout(() => {
					this.queryCanvas((canvas) => {
						this.context = this.lpapi.createDrawContext({
							canvas: canvas,
							canvasId: this.canvasId,
						});
					});
				}, 100);
			} else {
				this.context = this.lpapi.createDrawContext({
					// 用于进行标签绘制的画布ID
					canvasId: this.canvasId,
				});
			}
			//
			this.lpapi.setDrawContext(this.context);
		},
		onReady() {},
		methods: {
			async printConnect(index,item){
				if(item.deviceId===this.activeDeviceId) {
					uni.showToast({
						icon:'none',
						title:"断开成功!"
					})
					this.activeDeviceId = ""
					this.closePrinter()
					return
				}
				
				if(this.activeDeviceId) {
					this.closePrinter()
					await new Promise(ps=>setTimeout(ps,500))
					this.activeDeviceId = ""
				}
				this.activeDeviceId  = item.deviceId
				this.deviceIndex = index;
				this.openPrinter()
			},
			checkAndOpenPrinter() {
				return new Promise((resolve) => {
					this.openPrinter((res) => {
						resolve(res);
					});
				});
			},
			closePrinter() {
				this.lpapi.closePrinter();
			},
			getDevice() {
				return this.deviceList[this.deviceIndex];
			},
			async onDeviceFound(devices) {
				if (devices && devices.length > 0) {
					this.deviceList.splice(0)
					for (let item of devices) {
						if ((item.name + "").startsWith("YLF")) {
							this.deviceList.push(item);
							const advertisData = item.advertisData ? new Uint8Array(item.advertisData) : undefined;
							const advDataStr = advertisData ? LPAUtils.getHexStringOfBytes(advertisData) : "-";
						}
					}
				}
			},
			startDiscovery() {
				uni.showLoading({
					title: "搜索蓝牙中...",
				});
				this.lpapi.startBleDiscovery({
					timeout: 5000,
					deviceFound: (devices) => {
						this.onDeviceFound(devices);
					},
					adapterStateChange: (result) => {
						if (!result.discovering) {
							uni.hideLoading();
						}
					},
				});
			},
			isPrintJob() {
				return this.printMode > 2 || this.printMode < 1;
			},
			processForLark(result) {
				const dpi = result.dpi;
				if (this.isLark && this.lpapi && this.isPrintJob()) {
					if (this.isIOS()) {
						this.lpapi.Context.Dpi = dpi * 0.5;
					} else {
						this.lpapi.Context.Dpi = dpi * 0.33;
					}
				}
			},
			updateCanvas(jobInfo) {
				return new Promise((resolve) => {
					if (!this.printCanvas) {
						// 更新canvas大小；
						this.labelWidth = jobInfo.canvas.width;
						this.labelHeight = jobInfo.canvas.height;
						// 等 Canvas 大小更新后在执行后续绘制操作；
						setTimeout(() => {
							resolve(true);
						}, 100);
					} else {
						resolve(true);
					}
				});
			},
			printQrcode(e) {
				const {
					tenantName,
					useName,
					assetName,
					storageLocation,
					barcodeNumber
				} = e
				const api = this.lpapi;
				const labelWidth = 50;
				const labelHeight = 70;
				const margin = 2;
				const itemWidth = labelHeight * 0.5;
				const itemHeight = labelHeight * 0.5;
				const qrcodeWidth = 18; // 二维码大小
				const qrcodeTableWidth = 4; // 二维码和表格的间距
				//
				return this.checkAndOpenPrinter().then(() => {
					const jobInfo = api.startJob({
						width: labelWidth,
						height: labelHeight,
						orientation: 0,
						jobName: 'lpapi-ble',
					});
					if (!jobInfo) {
						console.warn("---------- 打印任务创建失败！----------");
						return;
					}
					//
					this.updateCanvas(jobInfo).then(() => {
						// 将整个打印区域分割成四个区域，分别进行四种旋转测试
						api.drawTable({
							x: 2,
							y: 1,
							width: 47,
							height: 68,
							rowCount: 7,
							columnCount: 2,
							lineWidth: 0.4,
							columnWidths: [15, 0, 25],
							horizontalAlignment: 30,
							cells: [{
									type: "qrcode",
									text: "https://cxcw.isunke.cn/h5/index.html#/pages/asset/search?id=" +
										barcodeNumber,
									width: 10,
									rowSpan: 2,
									columnSpan: 2,
									y: labelWidth / 2,
									x: labelWidth / 2
								},
								"",
								"",
								"",
								"资产单位",
								tenantName,
								"条码编号",
								barcodeNumber,
								"资产名称",
								assetName,
								"使用人",
								useName,
								"存放地点",
								storageLocation,
							],
						});
						api.commitJob({
							gapType: 255,
							darkness: 255,
						}).then((resp) => {
							return resp.statusCode === 0;
						});
					});
				});
			},
			openPrinter(callback) {
				const currDevice = this.getDevice();
				const isAlipay = this.isAlipay;
				if (currDevice && currDevice.deviceId) {
					uni.showLoading({
						title: "正在链接打印机..."
					});
					this.lpapi.openPrinter({
						name: currDevice.name,
						deviceId: currDevice.deviceId,
						// 如果打印机链接失败的话，可以尝试连续进行多次链接。
						tryTimes: 5,
						success: (resp) => {
							uni.hideLoading();
							uni.showToast({
								title: "打印机链接成功！",
								icon: "none"
							});
							this.activeDeviceId = currDevice.deviceId
							if (typeof callback === "function") {
								callback(true);
							}
						},
						fail: (resp) => {
							uni.hideLoading();
							uni.showToast({
								title: "打印机链接失败！" + currDevice.name + JSON.stringify(resp),
								icon: "none"
							});
							if (typeof callback === "function") {
								callback(false);
							}
						},
					});
				} else {
					uni.showToast({
						title: "未检测到打印机",
						icon: "none"
					});
					if (typeof callback === "function") {
						callback(false);
					}
				}
			},
		}
	}
</script>

<style scoped>
	.item {
		display: flex;
		background-color: #fff;
		padding: 10rpx;
		align-items: center;
	}

	.item+.item {
		margin-top: 10rpx;
	}

	.status {
		margin-right: 20rpx;
	}

	.name {
		flex: 1;
	}

	.status {
		width: 20rpx;
		height: 20rpx;
		background-color: red;
		border-radius: 100%;
	}

	.btn {
		background-color: aquamarine;
		margin-left: 10rpx;
		color: #fff;
		padding: 10rpx 16rpx;
		border-radius: 10rpx;
		background-color: red;
	}
	.active-btn{
		background-color: skyblue;
	}
</style>